extends CharacterBody2D

enum Controler {LEFT,RIGHT}

@export var control_by = Controler.LEFT
@export var speed_x = 0;
@export var speed_y = 0;

var has_bullet = true

const SPEED = 300.0
const JUMP_VELOCITY = -320.0

var died = false

# Get the gravity from the project settings to be synced with RigidBody nodes.
var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")

var goal_direction = 0
var goal_direction_speed = 5

@onready var bullet = preload("res://bullet.tscn")

func _input(event):
	if event.is_action_pressed("control_left") and control_by == Controler.LEFT:
		controled()
	elif event.is_action_pressed("control_right") and control_by == Controler.RIGHT:
		controled()

func _ready():
	self.velocity = Vector2(speed_x,speed_y)

#角色被控制(按钮按下)
func controled():
	
	if died:
		return
		
	if has_bullet:
		has_bullet = false
		var mbullet:CharacterBody2D = bullet.instantiate()
		get_parent().add_child(mbullet)
		var mspeed = Vector2(1,0).rotated(-$Sprite2DPointer.rotation)
		mbullet.position = self.position
		mbullet.bullet_owner = self
		if self.velocity.x < 0:
			mbullet.velocity = Vector2(self.velocity.x * 7,0).rotated(-abs($Sprite2DPointer.rotation) - 180);
		else:
			mbullet.velocity = Vector2(self.velocity.x * 7,0).rotated(-(90 - abs($Sprite2DPointer.rotation) ));
		
		return
	if self.is_on_floor():
		self.velocity.y = JUMP_VELOCITY

func _physics_process(delta):
	
	if died:
		return
	
	goal_direction += goal_direction_speed
	if abs(goal_direction) >= 60:
		goal_direction_speed *= -1
	
	$Sprite2DPointer.rotation_degrees = goal_direction + 120
	
	
	#记录碰撞前的速度
	var init_speed_x = velocity.x
	var init_speed_y = velocity.y
	
	$Sprite2DBullet.visible = has_bullet
	
	if self.velocity.x < 0:
		$AnimatedSprite2D.flip_h = true
		$Sprite2DPointer.offset.x = 20
		$Sprite2DBullet.offset.x = 10
		$Sprite2DPointer.rotation_degrees = -$Sprite2DPointer.rotation_degrees
	else:
		$AnimatedSprite2D.flip_h = false
		$Sprite2DPointer.offset.x = -20
		$Sprite2DBullet.offset.x = -10
	
	if not self.is_on_floor():
		if self.velocity.y < 0:
			$AnimatedSprite2D.play("jump")
		else:
			$AnimatedSprite2D.play("idle")
	elif abs(self.velocity.x) > 0:
		$AnimatedSprite2D.play("run")
	
	
	# Add the gravity.
	if not is_on_floor():
		velocity.y += gravity * delta
	
	move_and_slide()
	
	if is_on_wall():
		if init_speed_x > 0:
			self.velocity.x = -abs(self.speed_x)
		else:
			self.velocity.x = abs(self.speed_x)
	
func hitted():
	#self.hide()
	self.died = true
	$AnimatedSprite2D.play("died")
	var timer = get_tree().create_timer(0.3)
	await timer.timeout
	self.hide()

func pick():
	if not self.has_bullet:
		self.has_bullet = true
		return true
		
	return false
